<template>
  <inline-modal
    :title="'【' + (json ? json.lists.actDeModelName : '') + '】- 审批流程'"
    :visible="visible"
    @cancel="
      () => {
        $emit('cancel');
      }
    "
  >
    <template slot="button">
      <template
        v-if="flowNodeButtons.some((e) => e.nodeButtonCode === 'agree')"
      >
        <a-button
          v-for="(item, index) in flowNodeButtonAgree"
          :key="index"
          class="margin-buttom"
          type="primary"
          :loading="agreeLoading"
          @click="buttonEventBefore(item.nodeButtonCode, item.nodeButtonName)"
          >{{ item.nodeButtonName }}</a-button
        >
      </template>
      <a-dropdown
        v-if="flowNodeButtons.some((e) => e.nodeButtonCode != 'agree')"
      >
        <a-menu slot="overlay">
          <a-menu-item
            v-for="(item, index) in flowNodeButtonOther"
            :key="index"
            @click="buttonEventBefore(item.nodeButtonCode, item.nodeButtonName)"
            >{{ item.nodeButtonName }}</a-menu-item
          >
        </a-menu>
        <a-button style="margin-left: 8px">
          更多 <a-icon type="down" />
        </a-button>
      </a-dropdown>

      <a-button
        class="delete-btn margin-left-xs"
        @click="
          () => {
            $emit('cancel');
          }
        "
        >{{ $ct("close", "关闭") }}</a-button
      >
    </template>

    <a-tabs v-model="mode" @change="changeMode" class="formTab">
      <a-tab-pane key="1">
        <span slot="tab">
          <a-icon type="form" />
          {{ $ct("formFields", "表单信息") }}
        </span>

        <a-form ref="myform" :form="formOpinion" @submit="handleSubmit">
          <a-card class="missionForm">
            <template>
              <!-- <previewModal id="printForm" ref="previewModal" :drawingList="drawingList" @getJsonData="getJsonData" /> -->
              <component
                id="printForm"
                ref="previewModal"
                :form="formOpinion"
                :isView="isView"
                :drawingList="drawingList"
                @getJsonData="getJsonData"
                :is="plugItem"
                v-for="(plugItem, plugIndex) in plugs"
                :key="plugIndex"
              ></component>
            </template>
          </a-card>
          <a-card class="margin-top-sm" ref="secondCard">
            <template>
              <a-form-item :label="$ct('approvalComments', '审批意见')">
                <a-textarea
                  :rows="4"
                  v-decorator="[
                    'message',
                    { rules: [{ required: messageRequired, message: '必填' }] },
                  ]"
                />
              </a-form-item>
              <a-form-item class="hiddenItem">
                <a-input v-decorator="['processInstanceId']" type="hidden" />
              </a-form-item>
              <a-form-item class="hiddenItem">
                <a-input v-decorator="['taskId']" type="hidden" />
              </a-form-item>
              <a-form-item class="hiddenItem">
                <a-input v-decorator="['processDefinitionId']" type="hidden" />
              </a-form-item>
              <!-- <a-form-item label="">
                <a-checkbox
                  @change="changeDuplicate"
                  v-model="isDuplicate"
                /><span class="margin-left-xs">{{
                  $ct("CcOrNot", "是否抄送")
                }}</span>
              </a-form-item> -->
              <a-form-item :label="$ct('ccTo', '抄送给')" v-if="isDuplicate">
                <personnel-popup
                  placeholder="请选择抄送人"
                  @change="(value, data) => setUser(data, 1)"
                  :multiple="true"
                  v-decorator="[
                    'duplicateUser',
                    { rules: [{ required: true, message: '请选择抄送人！' }] },
                  ]"
                >
                </personnel-popup>
              </a-form-item>
              <a-form-item label="">
                <a-checkbox @change="changeAssign" v-model="isAssign" /><span
                  class="margin-left-xs"
                  >{{
                    $ct("SpecifyTheNextNodeHandler", "是否指定下一节点处理人")
                  }}</span
                >
              </a-form-item>
              <a-form-item :label="$ct('appoint', '指定')" v-if="isAssign">
                <a-alert
                  message="如果下一节点为会签，则指定处理人不生效"
                  banner
                />
                <personnel-popup
                  placeholder="请指定下一步处理人"
                  @change="(value, data) => setUser(data, 2)"
                  v-decorator="[
                    'assignUserName',
                    {
                      rules: [
                        { required: true, message: '请指定下一步处理人！' },
                      ],
                    },
                  ]"
                >
                </personnel-popup>
              </a-form-item>
              <a-form-item class="hiddenItem">
                <a-input v-decorator="['assignUser']" type="hidden" />
              </a-form-item>
              <a-form-item class="hiddenItem">
                <a-input v-decorator="['duplicateUserName']" type="hidden" />
              </a-form-item>
              <!-- <template v-for="(item, index) in flowNodeButtons">
                <a-button
                  class="margin-buttom"
                  type="primary"
                  html-type="submit"
                  :data-node="item.nodeButtonCode"
                  :data-name="item.nodeButtonName"
                  :style="{ marginRight: '8px' }"
                  @click="nodeButtonClick(item.nodeButtonCode)"
                  >{{ item.nodeButtonName }}</a-button
                >
              </template> -->
            </template>
          </a-card>
          <!-- <a-card class="margin-top-sm" title="审批记录">
            <a-table
              size="small"
              :rowKey="(record, index) => record.comment.id"
              :columns="columns"
              :data-source="dataList"
              :pagination="pagination"
            ></a-table>
          </a-card> -->
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="2">
        <span slot="tab">
          <a-icon type="picture" />
          {{ $ct("workflowChart", "流程图") }}
        </span>
        <bpmn-viewer
          ref="bpmView"
          :params="params"
          :inProgress="inProgress"
          :notInProgress="notInProgress"
          :nodeParam="nodeParam"
        ></bpmn-viewer>
      </a-tab-pane>
      <a-tab-pane key="3">
        <span slot="tab">
          <a-icon type="history" />
          {{ $ct("approvalRecord", "审批记录") }}
        </span>
        <comment-bean-list-vue ref="commentBeanListRef"
          :dataList="dataList" :commentParams="commentParams"></comment-bean-list-vue>
      </a-tab-pane>
    </a-tabs>

    <taskTransfer
      ref="taskTransfer"
      :title="transferTitle"
      :transferType="transferType"
      :confirmLoading="transferConfirmLoading"
      :model="taskModel"
      :visible="taskVisible"
      @cancel="
        () => {
          taskModel = null;
          taskVisible = false;
        }
      "
      @ok="handleTransfer"
    ></taskTransfer>
    <taskReject
      ref="taskReject"
      :title="rejectTitle"
      :rejectType="rejectType"
      :rejectList="rejectList"
      :model="rejectModel"
      :visible="taskRejectVisible"
      :confirmLoading="rejectConfirmLoading"
      @cancel="
        () => {
          taskRejectVisible = false;
        }
      "
      @ok="handleReject"
    ></taskReject>
    <!-- 按钮弹窗 -->
    <button-dialog
      ref="buttonDialogRef"
      :commentParams="commentParams"
      @ok="buttonDialogOk"
      @cancel="buttonDialogCancel"
    ></button-dialog>
  </inline-modal>
</template>

<script>
import BpmnViewer from "@/components/TopVUI/bpmn/Viewer";
import taskTransfer from "./taskTransfer.vue";
import taskReject from "./taskReject.vue";

import { deepClone } from "@/utils/index.js";
import { setTypeList, getTypeList, getTypeListByFiled } from "@/utils/formatter";
import pick from "lodash.pick";
import { PersonnelPopup } from "@/components";
import ButtonDialog from "@/components/TopVUI/custom/buttonDialog/index.vue"
import { loadButtonDialog, buttonEventInterceptor } from "@/components/TopVUI/custom/buttonDialog/index.js";
import commentBeanListVue from '../components/commentBeanList.vue';
// 表单字段
const fields = [
  "processInstanceId",
  "taskId",
  "message",
  "processDefinitionId",
  "duplicateUserName",
  "assignUserName",
  "assignUser",
  "duplicateUser",
];
const columns = [
  {
    title: "审核环节",
    dataIndex: "activityName",
    align: "center",
    langCode: "auditPhase",
  },
  {
    title: "审核人",
    dataIndex: "userName",
    align: "center",
    langCode: "ReviewedBy",
  },
  {
    title: "审核类型",
    dataIndex: "comment.type",
    align: "center",
    scopedSlots: {
      customRender: "type",
    },
    langCode: "AuditType",
  },
  {
    title: "审核意见",
    dataIndex: "comment.message",
    align: "center",
    langCode: "ReviewComments",
  },
  {
    title: "接收时间",
    dataIndex: "taskCreateTime",
    sorter: false,
    align: "center",
  },
  {
    title: "审核时间",
    dataIndex: "comment.time",
    sorter: false,
    align: "center",
    langCode: "AuditTime",
  },
];
export default {
  name: "TreeList",
  components: {
    BpmnViewer,
    taskTransfer,
    taskReject,
    PersonnelPopup,
    ButtonDialog,
    commentBeanListVue
  },
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    loading: {
      type: Boolean,
      required: true,
    },
    model: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      columns,
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 3,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 21,
        },
      },
      currentItem: "",
      index: "",
      drawingList: {},
      activeId: "",
      formConf: "",
      formOpinion: this.$form.createForm(this, { name: "dynamic_rule" }),
      type: "",
      fullscreen: true,
      isTask: true,
      mode: "1",
      params: "",
      dataList: [],
      inProgress: [],
      notInProgress: [],
      flowNodeButtons: [],
      uuid: "",
      tableName: "",
      formUuid: "",
      fieldList: {},
      btnType: "",
      taskModel: null,
      taskVisible: false,
      taskRejectVisible: false,
      transferConfirmLoading: false,
      rejectConfirmLoading: false,
      rejectList: [],
      rejectModel: null,
      transferType: 0,
      transferTitle: "",
      rejectType: 0,
      rejectTitle: "",
      printObj: {
        id: "printForm", //打印标签的id
        popTitle: "流程表单", //文件标题
        // extraCss: 'https://www.google.com,https://www.google.com',
        extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
      },
      nodeParam: {},
      plugs: [],
      modelType: 0,
      json: "",
      isDuplicate: false,
      isAssign: false,
      isView: true,
      outComeType: "",
      pagination: {
        pageSize: 5,
        hideOnSinglePage: true,
      },
      messageRequired: true,
      agreeLoading: false, // 同意按钮的loading
      currentBtn: {},
      commentParams: {}
    };
  },
  mounted() {
    this.params = ``;
    this.plugs = [];
    this.plugs.push(() =>
      import(
        `@/components/TopVUI/k-form-design/packages/KFormPreview/preview.vue`
      )
    );
  },
  created() {
    // 防止表单未注册
    fields.forEach((v) => this.formOpinion.getFieldDecorator(v));
    // 当 model 发生改变时，为表单设置值
    this.$watch("model", () => {
      this.model && this.formOpinion.setFieldsValue(pick(this.model, fields));
    });
  },
  computed: {
    flowNodeButtonAgree() {
      return this.flowNodeButtons.filter((e) => e.nodeButtonCode === "agree");
    },
    flowNodeButtonOther() {
      return this.flowNodeButtons.filter((e) => e.nodeButtonCode !== "agree");
    },
  },
  watch: {
    visible(val) {
      if (!val) {
        this.agreeLoading = val;
      }
    },
  },
  methods: {
    // 流程图信息
    changeMode(e) {
      this.mode = e;
      if (this.$refs.bpmView && this.mode == "4")
        this.$refs.bpmView.initDiagramAgain(
          this.json.lists.actDeModelId,
          this.json.lists.actDeModelKey,
          this.json.lists.actDeModelName,
          this.params
        );
    },
    // 加载办理数据
    async loadData(e, json) {
      this.mode = "1";
      this.formOpinion.setFieldsValue(pick(e, fields));
      this.isDuplicate = false;
      this.isAssign = false;
      this.json = json;
      this.modelType = json.lists.modelType;
      let flowNodeField = json.flowNodeField;
      this.modelKey = e.modelKey;
      this.uuid = e.businessKey;
      this.nodeParam = {
        procdefId: e.processDefinitionId,
        processInstanceId: e.processInstanceId,
      };
      if (this.modelType === "2") {
        //2为可视化，1为自定义
        this.plugs = [];
        this.plugs.push(() =>
          import(
            `@/components/TopVUI/k-form-design/packages/KFormPreview/preview.vue`
          )
        );
        //默认加载表单预览页面
        this.drawingList = JSON.parse(json.lists.formDesign);
        await this.formValReset(json);
        // 数据接收赋值
        if (json.formDetail) {
          if (Array.isArray(json.formDetail)) {
            this.drawingList.list.forEach((item) => {
              json.formDetail.forEach((obj) => {
                if (item.model === obj.tableField) {
                  item.options.defaultValue = obj.fieldValue;
                }
              });
            });
          } else {
            this.drawingList.list.forEach((item) => {
              if (json.formDetail.hasOwnProperty(item.model)) {
                // 检查json.formDetail中是否存在item.model作为键
                item.options.defaultValue = json.formDetail[item.model]; // 如果存在，则赋值
              }
            });
          }
        }
        // 先过滤显隐规则再过滤可查看可编辑
        this.handRules(this.drawingList);
        this.drawingList.list.forEach((e, index) => {
          getTypeListByFiled(e, flowNodeField);
        });
        // 老版本流程表单自定义布局排序
        // this.drawingList.list = this.sortArray(this.drawingList.list, flowNodeField);
        if (this.$refs.previewModal)
          this.$refs.previewModal.jsonData = this.drawingList; //表单数据设置
        this.tableName = json.lists.formTableName;
        loadButtonDialog(json.btnGroup, this);
      } else {
        this.plugs = [];
        this.drawingList = json.businessData;
        // import在本地运行时出错
        this.plugs.push((resolve) =>
          require([
            `@/pages${json.flowNodeButtons[0].nodeFormPath}.vue`,
          ], resolve)
        ); //动态加载外联表单页
        this.isView = Boolean(Number(json.flowNodeButtons[0].whetherUpdate));
        // if(this.$refs.previewModal) this.$refs.previewModal.drawingList = this.drawingList
      }
      this.params = json.lists.flowDesign;
      // if(this.$refs.bpmView) this.$refs.bpmView.initDiagramAgain(json.lists.actDeModelId,json.lists.actDeModelKey, json.lists.actDeModelName, this.params)		//流程数据设置
      // 流程处理意见参数
      this.commentParams = {
        procdefId: e.processDefinitionId,
        businessKey: json.businessKey,
        modelKey: e.modelKey,
        processInstanceId: e.processInstanceId
      }
      this.dataList = json.commentBeanList; //流程处理意见
      this.inProgress = json.inProgress; //正在走的结点数组
      this.notInProgress = json.notInProgress; //已走完的结点数组
      this.flowNodeButtons = json.flowNodeButtons; //路程处理按钮
      this.formUuid = json.lists.uuid;
    },
    // 编辑的时候处理显隐规则绑定后的数据
    handRules(value) {
      const rules = value.config.implicitRules;
      const data = value.list;
      rules?.forEach((rule) => {
        const {
          selectComponentId,
          selectTableId,
          selectValueLId,
          selectValueL,
          selectOtherComponentId,
          selectOtherTableId,
          ifShow,
          ifRequired,
        } = rule;
        const targetComponent = data.find(
          (item) =>
            item.key === selectOtherComponentId ||
            item.model === selectOtherTableId
        );
        let shouldHide = false;
        if (selectComponentId.startsWith("checkbox_")) {
          const selectComponent = data.find(
            (item) =>
              item.key === selectComponentId || item.model === selectTableId
          );
          const arr = selectComponent.options.defaultValue.split(",");
          shouldHide =
            ifShow === "show"
              ? !arr.includes(selectValueL)
              : arr.includes(selectValueL);
        } else if (
          selectComponentId.startsWith("input_") ||
          selectComponentId.startsWith("textarea_")
        ) {
          const selectComponent = data.find(
            (item) =>
              item.key === selectComponentId || item.model === selectTableId
          );
          if (selectComponent)
            shouldHide =
              ifShow === "show"
                ? selectComponent.options.defaultValue !== selectValueL
                : selectComponent.options.defaultValue === selectValueL;
        } else {
          const selectComponent = data.find(
            (item) =>
              item.key === selectComponentId || item.model === selectTableId
          );
          if (selectComponent)
            shouldHide =
              ifShow === "show"
                ? selectComponent.options.defaultValue !== selectValueL
                : selectComponent.options.defaultValue === selectValueL;
        }
        // 如果是必填组件，根据隐藏状态去除/增加必填属性
        if (targetComponent) {
          if (targetComponent.rules && ifRequired)
            targetComponent.rules[0].required = !shouldHide;
          targetComponent.options.hidden = shouldHide;
        }
        if (shouldHide) {
          targetComponent.options.defaultValue = "";
          const nestedTargetComponent = value.list.find(
            (item) =>
              item.key === selectOtherComponentId ||
              item.model === selectOtherTableId
          );
          nestedTargetComponent.options.hidden = true;
        }
      });
    },
    sortArray(arr1, arr2) {
      let result = [];
      for (let i = 0; i < arr2.length; i++) {
        let key = arr2[i].filed;
        for (let j = 0; j < arr1.length; j++) {
          if (arr1[j].key === key) {
            result[i] = arr1[j];
            break;
          } else if (j === arr1.length - 1) {
            result.push(arr1[j]);
          }
        }
      }
      return result;
    },
    toHump(name) {
      return name.replace(/\_(\w)/g, function(all, letter) {
        return letter.toUpperCase();
      });
    },
    // 流程处理节点人员设置
    changeDuplicate(e) {
      this.isDuplicate = e.target.checked;
      if (!this.isDuplicate) {
        this.formOpinion.setFieldsValue({
          duplicateUser: "",
          duplicateUserName: "",
        });
      }
    },
    // 下一节点处理人
    changeAssign(e) {
      this.isAssign = e.target.checked;
      if (!this.isAssign) {
        this.formOpinion.setFieldsValue({
          assignUser: "",
          assignUserName: "",
        });
      }
    },
    // 设置节点人员
    setUser(data, type) {
      let userName = data.map((e) => e.userName).toString();
      let userNameId = data.map((e) => e.userNameId).toString();
      if (type == 2) {
        this.formOpinion.setFieldsValue({
          assignUserName: userName,
          assignUser: userNameId,
        });
      } else {
        this.formOpinion.setFieldsValue({
          duplicateUserName: userName,
          duplicateUser: userNameId,
        });
      }
    },
    //保存是获取表单数据   表单流程适用
    getJsonData(fieldList) {
      if (this.modelType == "2") {
        this.fieldList = fieldList;
        this.drawingList.list.forEach((e, index) => {
          let obj = setTypeList(e, fieldList);
          e = obj.e;
          fieldList = obj.list;
        });
      }
      if (
        this.type === "agree" ||
        this.type === "reject" ||
        this.type == "onLine"
      ) {
        fieldList.outcome = this.outComeType;
        this.$emit("ok", this.type, this.drawingList, fieldList);
      } else if (this.type === "update") {
        this.handleUpdate();
      } else if (
        [
          "transfer",
          "withdraw",
          "delegate",
          "signatureBefore",
          "signatureAfter",
        ].includes(this.type)
      ) {
        this.taskVisible = true;
        const form = this.$refs.taskTransfer.form;
        form.resetFields(); // 清理表单数据（可不做）
        this.taskModel = this.model;
        this.taskModel.instanceId = this.model.processInstanceId;
        if (this.transferType === 4) {
          this.$refs.taskTransfer.typeNum = 2;
          this.taskModel.signature = "before";
        } else if (this.transferType === 5) {
          this.$refs.taskTransfer.typeNum = 2;
          this.taskModel.signature = "after";
        }
        // this.handleTransfer()
      } else if (["returnAnyNode", "termination"].includes(this.type)) {
        const form = this.$refs.taskReject.form;
        form.resetFields(); // 清理表单数据（可不做）
        this.taskRejectVisible = true;
        this.rejectModel = this.model;
        this.getBackNodesByProcessInstanceId();
      }
    },
    //获取可驳回节点列表
    getBackNodesByProcessInstanceId() {
      this.confirmLoading = true;
      this.$post("/workflow/apiFlowableTask/getBackNodesByProcessInstanceId", {
        taskId: this.model.taskId,
        processInstanceId: this.model.processInstanceId,
      }).then((res) => {
        if (res.statuCode != 300) {
          this.rejectList = res;
        }
        this.confirmLoading = false;
      });
    },
    async buttonEventBefore(value, name) {
      this.currentBtn = {
        code: value,
        name: name,
      };
      const config = {
        mainFormUuid: this.json.lists.formUuid, // 主表单uuid
        mainUuid: this.json.businessKey, // 主表单业务uuid
        mainForm: this.resetFormDetail, // 主表单数据
      };
      // 只有同意和驳回需要必须输入审批意见
      if(value === "agree" || value === "reject") {
        this.agreeLoading = true;
        this.messageRequired = true;
        await this.$nextTick()
        const validate = await this.validateMessage();
        const validateMore = await this.validateDuplicateUserAndAssignUserName();
        if(validate || validateMore) {
          this.agreeLoading = false;
          return
        }
      }else{
        this.messageRequired = false;
      }
      this.validate().then(res => {
        this.resetFormDetail = res.values;
        config.mainForm = res.values;
        buttonEventInterceptor(value, name, config).then(res => {
          if (!res) {
            this.nodeButtonClick(value, name);
          }else{
            this.agreeLoading = false;
          }
        });
      }).catch((err) => {
        this.$message.warning(err.message || "校验失败")
      })
    },
    nodeButtonClick(e, name) {
      if (this.modelType === "2") {
        this.$refs.previewModal[0]
          .validateForm()
          .validateFields((errors, values) => {
            if (!errors) {
              this.$refs.myform.onSubmit({ node: e, name });
            } else {
              this.$message.error("表单验证失败，请检查表单！", 1.5);
              this.agreeLoading = false;
            }
          });
      } else {
        this.$refs.myform.onSubmit({ node: e, name });
      }
      setTimeout(() => {
        this.agreeLoading = false;
      }, 1000);
    },
    // 表单提交
    handleSubmit(event) {
      // event.preventDefault(); // 阻止默认事件,防止表单提交刷新页面
      // e = event.submitter.dataset.node; //此获取方法不适用与所有浏览器，可切换handleAgree事件
      // title = event.submitter.dataset.name;
      let e = event.node;
      let title = event.name;
      this.type = e;

      let arr4 = [
        "transfer",
        "withdraw",
        "delegate",
        "signatureBefore",
        "signatureAfter",
      ];
      let arr5 = ["returnAnyNode", "termination"];

      // if (this.modelType === "1") {
      if (e == "agree" || e == "reject" || e == "onLine") {
        // const form = this.$refs.previewModal[0].form;
        this.formOpinion.validateFields((errors, values) => {
          if (!errors) {
            let formData = {};
            let pramar = {
            };
            if (this.modelType === "2") {
              this.drawingList.list.forEach((item) => {
                if (item.type === "card") {
                  item.list.forEach((val) => {
                    if (typeof val.options.defaultValue === "object") {
                      formData[val.model] = JSON.stringify(
                        val.options.defaultValue
                      );
                    } else {
                      formData[val.model] = val.options.defaultValue;
                    }
                  });
                } else if (~["grid", "tabs"].indexOf(item.type)) {
                  item.columns.forEach((val1) => {
                    val1.list.forEach((val2) => {
                      if (typeof val2.options.defaultValue === "object") {
                        formData[val2.model] = JSON.stringify(
                          val2.options.defaultValue
                        );
                      } else {
                        formData[val2.model] = val2.options.defaultValue;
                      }
                    });
                  });
                } else if (item.type === "table") {
                  item.trs.forEach((val1) => {
                    val1.tds.forEach((val2) => {
                      val2.list.forEach((val3) => {
                        if (typeof val3.options.defaultValue === "object") {
                          formData[val3.model] = JSON.stringify(
                            val3.options.defaultValue
                          );
                        } else {
                          formData[val3.model] = val3.options.defaultValue;
                        }
                      });
                    });
                  });
                } else {
                  if (typeof item.options.defaultValue === "object") {
                    formData[item.model] = JSON.stringify(
                      item.options.defaultValue
                    );
                  } else {
                    formData[item.model] = item.options.defaultValue;
                  }
                }
              });
              
              pramar = formData;
              values.formDesign = JSON.stringify(this.drawingList);
              values.formModel = JSON.stringify(this.drawingList.config);
            }
            if (pramar.list && pramar.list.length) {
              pramar.list = JSON.stringify(pramar.list);
            }
            
            pramar.tableName = this.tableName;
            pramar.uuid = this.uuid;
            values.outcome = title;
            values = Object.assign(values, pramar);
            values.formUuid = this.json.lists.formUuid;
            values.actDeModelKey = this.json.lists.actDeModelKey;
            values.businessKey = this.json.businessKey;
            values.taskNodeId = this.json.inProgress[0];
            // this.$emit("ok", values);
            this.$emit("ok", this.type, this.drawingList, values);
          }
          this.agreeLoading = false;
        });
      } else if (arr5.includes(e)) {
        this.rejectType = arr5.indexOf(e) + 1;
        this.rejectTitle = title;
        const form = this.$refs.taskReject.form;
        form.resetFields(["message"]); // 清理表单数据（可不做）单独清除备注/意见
        this.taskRejectVisible = true;
        this.rejectModel = this.model;
        this.getBackNodesByProcessInstanceId();
        // this.getJsonData();
      } else if (["update"].includes(e)) {
        // 判断是自己写的表单还是通过拖动出来的表单  1自己写的表单  2拖动设计的
        if (2 == this.modelType) {
          this.formOpinion.validateFields((errors, values) => {
            // if (!errors) { // 更新不验证
            this.handleUpdate();
            // }
          });
        } else {
          let nodeFormUpdatePath = this.flowNodeButtons[0].nodeFormUpdatePath;
          if (nodeFormUpdatePath) {
            // const form = this.$refs.previewModal[0].form;
            this.formOpinion.validateFields((errors, values) => {
              // if (!errors) { // 更新不验证
              this.$post(nodeFormUpdatePath, values).then((res) => {
                if (res.statusCode === 200) {
                  this.$message.success(res.message, 1.5);
                  this.$emit("close");
                } else {
                  this.$message.error(res.message, 1.5);
                }
              });
              // }
            });
          }
        }
      } else if (arr4.includes(e)) {
        let index = [
          "transfer",
          "withdraw",
          "delegate",
          "signatureBefore",
          "signatureAfter",
        ].indexOf(e);
        this.transferType = index + 1;
        this.transferTitle = title;
        this.taskVisible = true;
        const form = this.$refs.taskTransfer.form;
        form.resetFields(["comment", "userNameId"]); // 清理表单数据（可不做）为了防止取消再操作导致数据丢失，只清理可填写部分
        this.taskModel = this.model;
        this.taskModel.instanceId = this.model.processInstanceId;
        if (this.transferType === 4) {
          this.$refs.taskTransfer.typeNum = 2;
          this.taskModel.signature = "before";
        } else if (this.transferType === 5) {
          this.$refs.taskTransfer.typeNum = 2;
          this.taskModel.signature = "after";
        }
      } else if (e === "rejectPreviousStep") {
        const values = {
          processInstanceId: this.model.processInstanceId,
          currentActivityId: this.model.nodeId,
          processDefinitionId: this.model.processDefinitionId,
          taskId: this.model.taskId,
        };
        this.$post(
          "/workflow/apiFlowableTask/goBackToThePreviousStep",
          values
        ).then((res) => {
          if (res.statusCode === 200) {
            this.$message.success(res.message, 1.5);
            this.$emit("close");
          } else {
            this.$message.error(res.message, 1.5);
          }
        });
      }
    },
    // 流程按钮统一处理事件
    handleAgree(e, title) {
      let arr4 = [
        "transfer",
        "withdraw",
        "delegate",
        "signatureBefore",
        "signatureAfter",
      ];
      let arr5 = ["returnAnyNode", "termination"];
      let index = [
        "transfer",
        "withdraw",
        "delegate",
        "signatureBefore",
        "signatureAfter",
      ].indexOf(e);
      // if (this.modelType === "1") {
      if (e == "agree" || e == "reject" || e == "onLine") {
        // const form = this.$refs.previewModal[0].form;
        if (this.modelType === "1") {
          this.formOpinion.validateFields((errors, values) => {
            if (!errors) {
              values.outcome = title;
              this.$emit("ok", e, null, values);
            }
          });
        }
      } else if (arr5.includes(e)) {
        this.rejectType = arr5.indexOf(e) + 1;
        this.rejectTitle = title;
        this.type = e;
        this.getJsonData();
      } else if (["update"].includes(e)) {
        let nodeFormUpdatePath = this.flowNodeButtons[0].nodeFormUpdatePath;
        if (nodeFormUpdatePath) {
          // const form = this.$refs.previewModal[0].form;
          this.formOpinion.validateFields((errors, values) => {
            if (!errors) {
              this.$post(nodeFormUpdatePath, values).then((res) => {
                if (res.statusCode === 200) {
                  this.$message.success(res.message, 1.5);
                  this.$emit("close");
                } else {
                  this.$message.error(res.message, 1.5);
                }
              });
            }
          });
        }
      } else {
        if (arr4.includes(e)) {
          this.transferType = index + 1;
          this.transferTitle = title;
        } else if (arr5.includes(e)) {
          this.rejectType = arr5.indexOf(e) + 1;
          this.rejectTitle = title;
        }
        this.type = e;
        this.outComeType = title;
        if (this.modelType === "1") {
          this.getJsonData();
        } else {
          this.$refs.previewModal[0].getJsonData();
        }
      }
    },
    // 更新
    handleUpdate() {
      // this.nodeParam = {
      //   procdefId: e.processDefinitionId,
      //   processInstanceId: e.processInstanceId,
      // };
      let pramer = {
        uuid: this.formUuid,
        formDesign: JSON.stringify(this.drawingList),
        formModel: JSON.stringify(this.drawingList.config),
        processInstanceId: this.nodeParam.processInstanceId,
        procdefId: this.nodeParam.procdefId,
        actDeModelKey: this.json.lists.actDeModelKey,
      };
      // let pramar = this.fieldList;
      let pramar = {};
      if (this.modelType === "2") {
        this.drawingList.list.forEach((item) => {
          if (item.type === "card") {
            item.list.forEach((val) => {
              if (typeof val.options.defaultValue === "object") {
                pramar[val.model] = JSON.stringify(val.options.defaultValue);
              } else {
                pramar[val.model] = val.options.defaultValue;
              }
            });
          } else if (~["grid", "tabs"].indexOf(item.type)) {
            item.columns.forEach((val1) => {
              val1.list.forEach((val2) => {
                if (typeof val2.options.defaultValue === "object") {
                  pramar[val2.model] = JSON.stringify(
                    val2.options.defaultValue
                  );
                } else {
                  pramar[val2.model] = val2.options.defaultValue;
                }
              });
            });
          } else if (item.type === "table") {
            item.trs.forEach((val1) => {
              val1.tds.forEach((val2) => {
                val2.list.forEach((val3) => {
                  if (typeof val3.options.defaultValue === "object") {
                    pramar[val3.model] = JSON.stringify(
                      val3.options.defaultValue
                    );
                  } else {
                    pramar[val3.model] = val3.options.defaultValue;
                  }
                });
              });
            });
          } else {
            if (typeof item.options.defaultValue === "object") {
              pramar[item.model] = JSON.stringify(item.options.defaultValue);
            } else {
              pramar[item.model] = item.options.defaultValue;
            }
          }
        });
      }
      pramar.tableName = this.tableName;
      pramar.uuid = this.uuid;
      this.$emit("update", pramer, pramar);
    },
    //转办
    handleTransfer() {
      let transferUrl = "";
      const form = this.$refs.taskTransfer.form;
      form.validateFields((errors, values) => {
        if (!errors) {
          if (this.transferType === 1) {
            transferUrl = "/workflow/apiFlowableTask/transfer";
          } else if (this.transferType === 2) {
            transferUrl = "/workflow/apiFlowableTask/revokeProcess";
          } else if (this.transferType === 3) {
            transferUrl = "/workflow/apiFlowableTask/delegate";
          } else if (this.transferType === 4 || this.transferType === 5) {
            transferUrl = "/workflow/apiFlowableTask/signature";
          }
          this.transferConfirmLoading = true;
          this.$post(transferUrl, values).then((res) => {
            if (res.statusCode === 200) {
              this.taskVisible = false;
              this.$message.success(res.message, 1.5);
              this.$emit("close");
            } else {
              this.$message.error(res.message, 1.5);
            }
            this.transferConfirmLoading = false;
          });
        }
      });
    },
    // 驳回到任意节点
    handleReject() {
      let rejectUrl = "";
      const form = this.$refs.taskReject.form;
      form.validateFields((errors, values) => {
        if (!errors) {
          if (this.rejectType === 1) {
            rejectUrl = "/workflow/apiFlowableTask/reject";
          } else {
            rejectUrl =
              "/workflow/apiFlowableProcessInstance/stopProcessInstanceById";
          }
          this.rejectConfirmLoading = true;
          this.$post(rejectUrl, values).then((res) => {
            if (res.statusCode === 200) {
              this.taskRejectVisible = false;
              this.$message.success(res.message, 1.5);
              this.$emit("close");
            } else {
              this.$message.error(res.message, 1.5);
            }
            this.rejectConfirmLoading = false;
          });
        }
      });
    },
    // 新增当流程表单详情渲染时 使用最新的表单值
    formValReset(json) {
      this.$post("/form/formDatabase/formGetDetail", {
        uuid: json.businessKey,
        formUuid: json.lists.formUuid,
      }).then(async (res) => {
        const drawingList = deepClone(this.drawingList);
        let formDetail = res || {};
        if (Array.isArray(formDetail)) {
          let formDetailObj = {};
          formDetail.forEach((item) => {
            formDetailObj[item.tableField] = item.fieldValue;
          });
          formDetail = formDetailObj;
        }
        this.resetFormDetail = formDetail;
        if (this.drawingList && Array.isArray(drawingList.list)) {
          drawingList.list.forEach((item) => {
            if (item.type === "uploadFile2" || item.type === "uploadFileDoc") {
              if (!this.formUuidUpload) {
                this.formUuidUpload = json.businessKey;
              }
            }
            getTypeList(item, formDetail);
          });
          this.drawingList = drawingList;
          this.json.lists.formDesign = JSON.stringify(drawingList);
        }
      });
    },
    buttonDialogOk() {
      const { code, name } = this.currentBtn;
      this.nodeButtonClick(code, name);
    },
    buttonDialogCancel() {
      console.log("已取消执行")
    },
    validateMessage() {
      return new Promise((resolve, reject) => {
        this.formOpinion.validateFields(
          ["message"],
          { force: true },
          (errors) => {
            if (errors && errors.message) {
              this.$message.error("请输入审批意见!");
              // 滚动到审批意见区域
              if (this.$refs.secondCard) {
                this.$refs.secondCard.$el.scrollIntoView({
                  behavior: "smooth",
                });
              }
              resolve(errors);
            }else{
              resolve();
            }
          }
        );
        
      })
    },
    validateDuplicateUserAndAssignUserName() {
      return new Promise((resolve, reject) => {
        this.formOpinion.validateFields(
          ["duplicateUser", "assignUserName"],
          { force: true },
          (errors) => {
            if (errors) {
              if (
                errors.duplicateUser &&
                errors.duplicateUser.errors.length > 0
              ) {
                this.$message.error(errors.duplicateUser.errors[0].message);
              }else if (
                errors.assignUserName &&
                errors.assignUserName.errors.length > 0
              ) {
                this.$message.error(errors.assignUserName.errors[0].message);
              }
              resolve(errors);
            }else{
              resolve();
            }
          }
        )
      })
    },
    validate() {
      return new Promise((resolve, reject) => {
        if(this.$refs.previewModal && this.$refs.previewModal[0].getJsonDataForPromise) {
          this.$refs.previewModal[0].getJsonDataForPromise().then(res => {
            resolve(res)
          }).catch(err => {
            reject(new Error("表单验证失败，请检查表单！"))
          })
        }else{
          reject(new Error("组件加载失败，请刷新重试！"))
        }
      })
    },
  },
};
</script>

<style lang="less" scoped="scoped">
.ant-form {
  height: auto;
  width: 100%;
}

/* .ant-modal-footer {
    border: none !important;
  } */

/deep/ .ant-card {
  /* box-shadow: rgba(0, 0, 0, 0.1) 0px 5px 20px 0px !important; */
}
/deep/ .my-bpmn-con .bpmn-viewer-content {
  height: calc(100vh - 120px) !important;
}
/deep/.my-bpmn-con .bpmn-viewer-content {
  height: calc(100vh - 120px) !important;
}
.missionForm {
  /* height: calc(100vh - 605px) !important; */
  /* overflow: hidden;
	   overflow-y: auto; */
}
/deep/.formTab.ant-tabs.ant-tabs-top.ant-tabs-line {
  height: calc(100vh - 210px) !important;
}
/deep/.ant-tabs-tabpane.ant-tabs-tabpane-active {
  overflow: auto;
  height: calc(100vh - 266px) !important;
}
.page-common-layout .page-common-content .ant-tabs-content .ant-card {
  height: auto !important;
}
</style>
